<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\bookpack;


use app\common\model\bookpack\BookpackAssociation;
use app\common\model\bookpack\Bookpack;
use app\common\logic\BaseLogic;
use app\common\service\FileService;
use think\facade\Db;


/**
 * BookpackAssociation逻辑
 * Class BookpackAssociationLogic
 * @package app\adminapi\logic
 */
class BookpackAssociationLogic extends BaseLogic
{

    /**
     * @notes 获取全部关联书籍
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author likeadmin
     * @date 2024/01/11 19:06
     */
    public static function getAll(array $params): array
    {
        $where = [];
        $where[] = ['ba.bookpack_id','=',$params['bookpack_id']];
        if (!empty($params['sort_id'])){
            $where[] = ['b.sort_id','=',$params['sort_id']];
        }
        if (!empty($params['channel_type'])){
            $where[] = ['b.channel_type','=',$params['channel_type']];
        }

        if (!empty($params['book_name'])){
            $where[] = ['b.book_name','like','%'.$params['book_name'].'%'];
        }

        $booklist = BookpackAssociation::alias('ba')
            ->join('book b', 'b.id = ba.book_id')->join('category c', 'b.sort_id = c.id')
            ->where($where)
            ->field(['ba.id', 'ba.book_id', 'ba.bookpack_id', 'ba.sort', 'b.book_name', 'b.thumb', 'b.channel_type', 'b.sort_id','b.book_type','c.name as category_name'])
            ->order(['sort' => 'asc'])
            ->select()
            ->toArray();
        foreach ($booklist as &$item){
            $item['thumb'] = FileService::getFileUrl($item['thumb']);
        }
        return $booklist;
    }


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/01/11 19:06
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            BookpackAssociation::create([
                'book_id' => $params['book_id'],
                'bookpack_id' => $params['bookpack_id'],
                'sort' => $params['sort']??0,
            ]);
            $num = BookpackAssociation::where('bookpack_id',$params['bookpack_id'])->count();
            Bookpack::where('id', $params['bookpack_id'])->update([
                'num' => $num,
            ]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/01/11 19:06
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            BookpackAssociation::where('id', $params['id'])->update([
                'book_id' => $params['book_id'],
                'bookpack_id' => $params['bookpack_id'],
                'sort' => $params['sort'],
            ]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * @notes 书籍置顶
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/01/11 19:06
     */
    public static function stickToTop(array $params): bool
    {
        Db::startTrans();
        try {
            $minSort = BookpackAssociation::where('bookpack_id',$params['bookpack_id'])->min('sort');

            // 将选定书籍的sort值更新为当前最小sort值
            BookpackAssociation::where('id', $params['id'])->update(['sort' => $minSort]);

            // 将其他书籍的sort值依次递增
            $books = BookpackAssociation::where('id', '<>', $params['id'])->where('bookpack_id',$params['bookpack_id'])->order('sort')->select();
            $sort = 2;
            foreach ($books as $book) {
                $book->sort = $sort;
                $book->save();
                $sort++;
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }
    /**
     * @notes 书籍置底
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/01/11 19:06
     */
    public static function stickToBottom(array $params): bool
    {
        Db::startTrans();
        try {
            $maxSort = BookpackAssociation::where('bookpack_id',$params['bookpack_id'])->max('sort');

            // 将选定书籍的sort值更新为当前最大sort值
            BookpackAssociation::where('id', $params['id'])->update(['sort' => $maxSort]);

            // 将其他书籍的sort值依次递增
            $books = BookpackAssociation::where('id', '<>', $params['id'])->where('bookpack_id',$params['bookpack_id'])->order('sort')->select();
            $sort = 1;
            foreach ($books as $book) {
                $book->sort = $sort;
                $book->save();
                $sort++;
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }
    /**
     * @notes 前移书籍
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/01/11 19:06
     */
    public static function moveUp(array $params): bool
    {
        Db::startTrans();
        try {
            // 获取选定书籍的sort值
            $selectedBook = BookpackAssociation::where('id',$params['id'])->find();
            $selectedSort = $selectedBook->sort;
            // 获取前一本书的sort值
            $prevBook = BookpackAssociation::where('sort', '<', $selectedSort)->where('bookpack_id',$params['bookpack_id'])->order('sort', 'desc')->find();
            if ($prevBook) {
                $prevSort = $prevBook->sort;

                // 交换选定书籍和前一本书的sort值
                $selectedBook->sort = $prevSort;
                $prevBook->sort = $selectedSort;

                // 保存修改
                $selectedBook->save();
                $prevBook->save();
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }
    /**
     * @notes 修改排序值
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/01/11 19:06
     */
    public static function moveDown(array $params): bool
    {
        Db::startTrans();
        try {
            // 获取选定书籍的sort值
            $selectedBook = BookpackAssociation::where('id',$params['id'])->find();
            $selectedSort = $selectedBook->sort;

            // 获取后一本书的sort值
            $nextBook = BookpackAssociation::where('sort', '>', $selectedSort)->where('bookpack_id',$params['bookpack_id'])->order('sort')->find();
            if ($nextBook) {
                $nextSort = $nextBook->sort;

                // 交换选定书籍和后一本书的sort值
                $selectedBook->sort = $nextSort;
                $nextBook->sort = $selectedSort;

                // 保存修改
                $selectedBook->save();
                $nextBook->save();
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * @notes 修改排序值
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/01/11 19:06
     */
    public static function updateSort(array $params): bool
    {
        Db::startTrans();
        try {
            BookpackAssociation::where('id', $params['id'])->update([
                'sort' => $params['sort'],
            ]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * @notes 修改书籍
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/01/11 19:06
     */
    public static function updateBook(array $params): bool
    {
        Db::startTrans();
        try {
            BookpackAssociation::where('id', $params['id'])->update([
                'book_id' => $params['book_id'],
            ]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/01/11 19:06
     */
    public static function delete(array $params): bool
    {

        Db::startTrans();
        try {
            BookpackAssociation::destroy($params['id']);
            $num = BookpackAssociation::where('bookpack_id',$params['bookpack_id'])->count();
            Bookpack::where('id', $params['bookpack_id'])->update([
                'num' => $num,
            ]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/01/11 19:06
     */
    public static function detail($params): array
    {
        return BookpackAssociation::findOrEmpty($params['id'])->toArray();
    }
}